package com.seek.inter;

import com.alibaba.fastjson.JSONObject;
import com.seek.authcheck.constants.AuthConstant;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.constants.ApiParamsConstant;
import com.seek.constants.RedisCustomerConstant;
import com.seek.inter.interdto.InterDtoCUser;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TCustomerCertify;
import com.seek.service.CustomerCertifyService;
import com.seek.service.CustomerService;
import com.seek.service.RegionInfoService;
import com.seek.util.CommonUtil;
import com.seek.util.DateUtil;
import com.sinovatech.common.config.GlobalConfig;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 实名认证相关接口
 * Created by weh on 2017/7/5.
 */
public class CustomerCertifyInter {

  private CustomerCertifyService customerCertifyService = (CustomerCertifyService) SpringContextHolder
      .getBean("customerCertifyService");

  private CustomerService customerService = (CustomerService) SpringContextHolder
      .getBean("customerService");

  private RegionInfoService regionInfoService = (RegionInfoService) SpringContextHolder
      .getBean("regionInfoService");


  /**
   * 保存提交的实名认证信息
   **/
  @Transactional
  public ResultInfo saveCustomerCertify(HttpServletRequest request, JSONObject reqJson)
      throws Exception {
    ResultInfo result = new ResultInfo();
    String token = reqJson.getString(ApiParamsConstant.TOKEN);
    Long custId = CommonUtil.getLongValue(reqJson.getString(ApiParamsConstant.CUST_ID));
    Long companyId = CommonUtil.getLongValue(reqJson.getString(ApiParamsConstant.COMPANY_ID));

    String custName = reqJson.getString(ApiParamsConstant.CUST_NAME);
    String cardNo = reqJson.getString(ApiParamsConstant.CARD_NUMBER);
    Date birthDay = null;
    Integer age = null;
    Integer sex = null;
    String cardCity = null;
    if (StringUtils.isNotEmpty(cardNo) && (cardNo.length() == 18 || cardNo.length() == 15)) {
      String bitrh = "";
      String sexNo = "";
      cardCity = StringUtils.substring(cardNo, 0, 4);
      if (cardNo.length() == 18) {
        bitrh = StringUtils.substring(cardNo, 6, 14);
        sexNo = StringUtils.substring(cardNo, 16, 17);
      } else {
        bitrh = "19" + StringUtils.substring(cardNo, 6, 12);
        sexNo = StringUtils.substring(cardNo, 14);
      }
      sex = Integer.valueOf(sexNo) % 2 == 0 ? 2 : 1;
      birthDay = DateUtil.getDateByString(bitrh, DateUtil.DATE_FORMAT_SHORT_YMD);
      age = getAge(birthDay);

    } else {
      result.setStatus(1);
      result.setMessage("证件号码错误或没有输入！");
      return result;
    }

    String regCity = reqJson.getString(ApiParamsConstant.REG_CITY);
    String regAddress = reqJson.getString(ApiParamsConstant.REG_ADDR);
    String img1 = reqJson.getString(ApiParamsConstant.IMG1);
    String img2 = reqJson.getString(ApiParamsConstant.IMG2);
    String img3 = reqJson.getString(ApiParamsConstant.IMG3);
    String fileUrl = GlobalConfig.getProperty("main", "file_cdn_url");

    img1 = StringUtils.replace(img1,fileUrl+fileUrl,fileUrl);
    img2 = StringUtils.replace(img2,fileUrl+fileUrl,fileUrl);
    img3 = StringUtils.replace(img3,fileUrl+fileUrl,fileUrl);
    String customerSql =
        "update t_customer set name = ? ,card_number = ? ,birthday = ? ,sex = ? , age = ? , status = ? , "
            + "certification_status = ?  where id = ? and company_id = ?";
    customerService.executeUpdate(customerSql,
        new Object[]{custName, cardNo, new java.sql.Date(birthDay.getTime()), sex, age, 1, 1, custId, companyId});

    customerCertifyService
        .executeUpdate("delete from t_customer_certify where customer_id = ? and company_id = ?",
            new Object[]{custId, companyId});
    TCustomerCertify certify = new TCustomerCertify();

    certify.setCustomerId(custId);
    certify.setCompanyId(companyId);
    certify.setImg1(img1);
    certify.setImg2(img2);
    certify.setImg3(img3);
    certify.setSubmitTime(new Date());
    certify.setAuditStatus(0);
    certify.setRegCity(regCity);
    certify.setRegAddress(regAddress);
    certify.setCardCity(cardCity);
    certify
        .setCardCity(regionInfoService.getCityByCardNo(cardNo));

    customerCertifyService.save(certify);
    Map<String, Object> cacheData = new HashMap<>();
    cacheData.put(RedisCustomerConstant.CUST_NO, cardNo);
    cacheData.put(RedisCustomerConstant.CUST_NAME, custName);
    cacheData.put(RedisCustomerConstant.CERT_STATUS, AuthConstant.AUTH_PROCESS);
    CacheUtil.refreshCustRedis(token, cacheData);

    result.setStatus(0);
    result.setMessage("操作成功");
    return result;

  }


  /**
   * 获取实名认证信息
   **/
  public ResultInfo getCustomerCertify(HttpServletRequest request, JSONObject reqJson) {
    ResultInfo result = new ResultInfo();
    Long custId = CommonUtil.getLongValue(reqJson.getString(ApiParamsConstant.CUST_ID));
    Long companyId = CommonUtil.getLongValue(reqJson.getString(ApiParamsConstant.COMPANY_ID));

    String query =
        "select ifnull(b.card_number,'') as cardNumber,  ifnull(b.name,'') as custName,a.img_1 as img1,a.img_2 as img2,"
            + "a.img_3 as img3,DATE_FORMAT(a.submit_time,'%Y-%m-%d %H:%i:%s') as submitTime,"
            + "DATE_FORMAT(a.audit_time,'%Y-%m-%d %H:%i:%s') as auditTime,a.audit_status as auditStatus,"
            + "a.audit_remark as auditRemark from t_customer_certify a,t_customer b where a.customer_id = b.id and "
            + "a.company_id = b.company_id and  a.company_id = ? and a.customer_id= ?";

    Map<String, Object> data = customerCertifyService
        .findOneMapBySql(query, new Object[]{companyId, custId});
    if (MapUtils.isNotEmpty(data)) {
      result.setStatus(0);
      result.setBody(data);
    } else {
      result.setStatus(1);
      result.setMessage("没有查询到实名认证信息");
    }

    return result;
  }

  /**
   * 获取年龄
   **/
  private int getAge(Date birth) {
    Calendar birthCalendar = Calendar.getInstance();
    birthCalendar.setTime(birth);

    Calendar nowCalendar = Calendar.getInstance();
    nowCalendar.setTime(new Date());

    int year = nowCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR);
    int month = nowCalendar.get(Calendar.MONTH) - birthCalendar.get(Calendar.MONTH);
    int date = nowCalendar.get(Calendar.DATE) - birthCalendar.get(Calendar.DATE);
    if (date < 0) {
      month--;
    }
    if (month < 0) {
      year--;
    }
    return year;

  }

}
